<template>
  <div class="my-order-page">
    <el-card shadow="never" class="filter-card">
      <template #header>
        <div class="filter-header">
          <h2>📝 我的订单</h2>
          <el-radio-group v-model="filterStatus" size="small" @change="loadOrders">
            <el-radio-button :label="undefined">全部</el-radio-button>
            <el-radio-button :label="1">待支付</el-radio-button>
            <el-radio-button :label="2">已支付</el-radio-button>
            <el-radio-button :label="3">已取消</el-radio-button>
          </el-radio-group>
        </div>
      </template>

      <!-- 空态 -->
      <div v-if="orders.length === 0" class="empty-box">
        <el-empty description="暂无订单，快去下单吧~" />
      </div>

      <!-- 订单列表 -->
      <div v-else class="order-list">
        <div v-for="o in orders" :key="o.id" class="order-item">
          <!-- 左侧时间线 -->
          <div class="line-dot"></div>
          <div class="line"></div>

          <!-- 右侧卡片 -->
          <el-card shadow="hover" class="order-card">
            <!-- 头部 -->
            <template #header>
              <div class="order-header">
                <div>
                  <span class="order-id">#{{ o.id }}</span>
                  <span class="table-num">桌台 {{ o.tableId ?? '打包' }}</span>
                  <span class="order-time">{{ new Date(o.createTime).toLocaleString() }}</span>
                </div>
                <el-tag :type="tagType(o.status)" effect="light" round>
                  {{ statusText(o.status) }}
                </el-tag>
              </div>
            </template>

            <!-- 菜品明细 -->
            <div v-for="it in o.items" :key="it.dishId" class="dish-row">
              <span>{{ it.dishName }}</span>
              <span class="qty">× {{ it.quantity }}</span>
              <span class="price">¥{{ (it.price * it.quantity).toFixed(2) }}</span>
            </div>

            <!-- 合计 -->
            <div class="total-row">
              合计：<span class="total-price">¥{{ o.totalPrice.toFixed(2) }}</span>
            </div>

            <!-- 新增：门店信息 -->
            <div class="store-row">
              门店：<span class="store-name">{{ getStoreName(o.storeId) }}</span>
            </div>

            <!-- 操作按钮 -->
            <div v-if="o.status === 1" class="action-bar">
              <el-button type="primary" size="small" @click="doPay(o.id)">支付</el-button>
              <el-button size="small" plain @click="doCancel(o.id)">取消</el-button>
            </div>
          </el-card>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/auth'
import { useCustomerStore } from '@/stores/customer'
import { getMyOrders, payOrder, cancelOrder } from '@/api/order'
import type { MyOrderVO } from '@/api/order'
import { useRouter } from 'vue-router'

const auth = useAuthStore()
const customer = useCustomerStore()
const userId = computed(() => auth.payload?.sub)
const router = useRouter()

const filterStatus = ref<1 | 2 | 3 | undefined>(1)
const orders = ref<MyOrderVO[]>([])

/* 工具函数 */
const tagType = (s: 1 | 2 | 3) => ({ 1: 'warning', 2: 'success', 3: 'info' } as const)[s]
const statusText = (s: 1 | 2 | 3) => ({ 1: '待支付', 2: '已支付', 3: '已取消' } as const)[s]

/* 根据 storeId 展示门店名称 */
const getStoreName = (id?: number) =>
  id === customer.store?.id ? customer.store.storeName : '—'

/* 加载订单 */
async function loadOrders() {
  if (!userId.value) return
  try {
    const { data: res } = await getMyOrders(userId.value, filterStatus.value)
    orders.value = Array.isArray(res.data) ? res.data : []
  } catch {
    ElMessage.error('获取订单失败')
    orders.value = []
  }
}

/* 支付 / 取消 */
async function doPay(id: number) {
  router.push(`/customer/pay/${id}`)
}

async function doCancel(id: number) {
  try {
    await cancelOrder(id)
    ElMessage.success('已取消')
    loadOrders()
  } catch (e: any) {
    ElMessage.error(e.response?.data?.message || '取消失败')
  }
}

onMounted(() => {
  loadOrders()
})

watch(filterStatus, loadOrders)
</script>

<style scoped>
.my-order-page {
  padding: 24px;
  background: #f7f9fb;
  min-height: 100vh;
}

.filter-card {
  border-radius: 12px;
  overflow: hidden;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-header h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
}

.empty-box {
  padding: 60px 0;
}

/* 时间线 */
.order-list {
  margin-left: 20px;
  position: relative;
}

.order-item {
  position: relative;
  margin-bottom: 24px;
  display: flex;
  align-items: flex-start;
}

.line-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  background: #409eff;
  margin-right: 12px;
  flex-shrink: 0;
  z-index: 1;
}

.line {
  position: absolute;
  left: 5px;
  top: 12px;
  width: 2px;
  height: calc(100% - 12px);
  background: #dcdfe6;
}

.order-card {
  flex: 1;
  border-radius: 10px;
  overflow: hidden;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.order-id {
  font-weight: 600;
  color: #303133;
}

.table-num {
  margin-left: 8px;
  color: #606266;
}

.order-time {
  margin-left: 8px;
  color: #909399;
  font-size: 13px;
}

.dish-row {
  display: grid;
  grid-template-columns: 1fr 40px 70px;
  gap: 8px;
  align-items: center;
}

.price {
  color: #f56c6c;
  font-weight: 500;
}

.store-row {
  margin-top: 8px;
  font-size: 14px;
  color: #606266;
}

.store-name {
  color: #303133;
  font-weight: 500;
}

.total-row {
  text-align: right;
  font-size: 15px;
  font-weight: 600;
  margin-top: 8px;
}

.total-price {
  color: #f56c6c;
  font-size: 16px;
}

.action-bar {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 12px;
}
</style>